/*
 * @Descripttion : 带排序的图片集
 * @Author       : QianFox Team
 * @Date         : 2022-03-21 09:41:46
 * @LastEditors  : QianFox Team
 * @LastEditTime : 2024-08-07 09:20:27
 */

import { imagesManager } from './imagesManager';

function ImageSort() {
    this.CONTAINER = '.foxui-images';
    this.DRAG = '.foxui-drag';
    this.CARD = '.foxui-images-card';
    this.LIST = '.foxui-images-list';
    this.LIST_ITEM = '.foxui-images-list > .foxui-images-item';
    this.ITEM = '.foxui-images-item';
    this.HANDLE = '.foxui-images-handle';
    this.DELETE_HANDLE = '.foxui-images .foxui-images-list .foxui-images-item .delete';
    this.REPLACE_HANDLE = '.foxui-images .foxui-images-item .replace';

    this.$this = null; // 当前图片集的点击目标 jQuery 对象
}

/**
 * @description: 初始化
 * @param {*}
 * @return {*}
 * @Date: 2022-04-14 16:33:23
 */
ImageSort.prototype._init = function () {
    this._judgeImageCount();
    this._bindDeleteImage();
    this._bindAddImage();
    this._bindReplaceImage();
    this._addCustomer();
};

/**
 * @description: 判断图片数量是否显示添加图片按钮
 * @param {*} container            容器节点（不传时为初始化）
 * @return {*}
 * @Date: 2022-03-21 11:20:34
 */
ImageSort.prototype._judgeImageCount = function ($container) {
    let that = this;
    $container = $container || $(this.CONTAINER);
    $container.each(function () {
        let $this = $(this),
            $handle = $this.find(that.HANDLE),
            count = $this.attr('data-count') || 1,
            len = $this.find(that.LIST_ITEM).length || 0;

        if (count > 0) {
            len < count ? $handle.show() : $handle.hide();
        }
    });
};

/**
 * @description: 绑定删除图片
 * @return {*}
 * @Date: 2022-03-21 14:04:56
 */
ImageSort.prototype._bindDeleteImage = function () {
    let that = this;
    $(document).on('click', that.DELETE_HANDLE, function () {
        let $this = $(this),
            $container = $this.closest(that.CONTAINER),
            $item = $this.closest(that.ITEM);

        $item.removeClass('foxui-animate-fadeInDown').addClass('foxui-animate-slideOutUp');
        setTimeout(() => {
            $item.remove();
            // 判断图片数量
            that._judgeImageCount($container);
        }, 300);
    });
};

/**
 * @description: 绑定添加图片
 * @param {*}
 * @return {*}
 * @Date: 2022-04-14 16:28:58
 */
ImageSort.prototype._bindAddImage = function () {
    let that = this;
    $(document).on('click', this.HANDLE, function () {
        imagesManager.show(this);
        that.$this = $(this);
    });
};

/**
 * @description: 绑定替换图片
 * @param {*}
 * @return {*}
 * @Date: 2022-04-14 16:35:27
 */
ImageSort.prototype._bindReplaceImage = function () {
    let that = this;
    $(document).on('click', this.REPLACE_HANDLE, function () {
        imagesManager.show(this);
        that.$this = $(this);
    });
};

/**
 * @description: 更新图片
 * @param {*} choosedList
 * @param {*} target
 * @return {*}
 * @Date: 2022-04-22 16:54:16
 */
ImageSort.prototype._updateImages = function ({ choosedList, target }) {
    // 如果没点击 foxui-images，则无需更新
    if (!this.$this) {
        return false;
    }
    // 点击 foxui-images，但中间退出，又点击别的节点，也无需更新
    if (target !== this.$this[0]) {
        return false;
    }
    // 更新节点
    let $this = this.$this,
        $container = $this.closest(this.CONTAINER);
    // 判断是追加还是替换
    let isAppend = $this.hasClass('foxui-images-handle');
    if (isAppend) {
        let count = $container.attr('data-count') || 1;
        let len = $container.find(this.LIST_ITEM).length || 0;
        // 判断并调整图片数量
        if (count > 0) {
            if (count - len > 0) {
                choosedList = choosedList.slice(0, count - len);
            } else {
                choosedList = [];
            }
        }
        $this.before(this._imageItmeHtml(choosedList));
        // 判断图片数量
        this._judgeImageCount($container);
    } else {
        let { id, url } = choosedList[0];
        $this.siblings('img').attr({ 'data-id': id, src: url });
    }
    // 修正订阅者（触发别的组件时，也可能会出现添加图片）
    this.$this = null;
};

ImageSort.prototype._imageItmeHtml = function (choosedList) {
    let $this = this.$this,
        isDrag = $this.closest(this.CONTAINER).is(this.DRAG);
    if (isDrag) {
        let htmlArr = [];
        choosedList.forEach(item => {
            htmlArr.push(this._imgLiDragHtml(item.id, item.url));
        });
        return htmlArr;
    } else {
        let htmlArr = [];
        choosedList.forEach(item => {
            htmlArr.push(this._imgLiHtml(item.id, item.url));
        });
        return htmlArr;
    }
};

ImageSort.prototype._imgLiDragHtml = function (id, url) {
    return [
        '<li class="foxui-images-item foxui-drag-item foxui-animate-fadeInDown">',
        '<div class="content">',
        `<img data-id="${id || ''}" src="${url}" />`,
        '<div class="foxui-drag-handle"></div>',
        '<span class="replace">替换</span>',
        '<i class="foxui-icon-cuowu-f delete"></i>',
        '</div>',
        '</li>',
    ].join('');
};

ImageSort.prototype._imgLiHtml = function (id, url) {
    return [
        '<li class="foxui-images-item foxui-animate-fadeInDown">',
        '<div class="content">',
        `<img data-id="${id || ''}" src="${url}">`,
        '<span class="replace">替换</span>',
        '<i class="foxui-icon-cuowu-f delete"></i>',
        '</div>',
        '</li>',
    ].join('');
};

/**
 * @description: 添加观察者
 * @param {*}
 * @return {*}
 * @Date: 2022-04-18 17:23:37
 */
ImageSort.prototype._addCustomer = function () {
    imagesManager._onConfirm(this._updateImages.bind(this));
};

let imageSort = new ImageSort();

export { imageSort };
